#include "logWindows.h"

#ifdef _WIN32

xxhhdzl::log::log(size_t flag)
    : lwLog(flag)
{}

xxhhdzl::log::~log()
{
    switch (_flag)
    {
    case 0:
        outputClassfile();
        break;
    case 1:
        break;
    case 2:
        outputOnefile();
        break;
    case 3:
        outputOnefile();
        break;
    case 4:
        outputClassfile();
        break;
    default:
        operator()(Error, 98, "flag set error");
        for (auto s : _log)
        {
            std::cout << s << std::endl;
        }
        break;
    }
}

bool xxhhdzl::log::outputOnefile()
{
    FILE* fd = fopen("./log.log", "a");
    if (fd == nullptr)
    {
        operator()(Error, __LINE__, "uotputOnefile create file lose");
        return false;
    }

    for (auto s : _log)
    {
        int c = fwrite(s.c_str(), sizeof(s[0]), s.size(), fd);
        if (c == 0)
        {
            operator()(Error, __LINE__, "write file all lose");
            return false;
        }
        else if (c > 0 && c < s.size())
        {
            operator()(Error, __LINE__, "write a portion");
            return false;
        }
    }
    fclose(fd);
    return true;
}

bool xxhhdzl::log::outputClassfile()
{
    //����Ŀ¼
    if (!CreateDirectoryA("./log", nullptr))
    {
        DWORD err = GetLastError();
        if (err != ERROR_ALREADY_EXISTS)
        {
            operator()(Error, __LINE__, "create directory failed, error: %d", err);
            return false;
        }
    }

    //��Ŀ¼�´��������־�ļ�
    std::vector<FILE*> fd(6);
    for (int i = 0; i <= 5; i++)
    {
        std::string s = "./log/";
        s += "log_" + getGrade(i);
        s += ".log";
        FILE* c = fopen(s.c_str(), "a");
        if (c == nullptr)
        {
            operator()(Error, __LINE__, "uotputClassfile create file lose");
            return false;
        }
        fd[i] = c;
    }

    for (auto s : _log)
    {
        int end = s.find("]");
        std::string t = s.substr(1, end - 1);

        int c = fwrite(s.c_str(), sizeof(s[0]), s.size(), fd[Grade(t)]);
        if (c == 0)
        {
            operator()(Error, __LINE__, "write file all lose");
            return false;
        }
        else if (c > 0 && c < s.size())
        {
            operator()(Error, __LINE__, "write a portion");
            return false;
        }
    }

    for (auto f : fd)
    {
        if (fclose(f) != 0)
        {
            operator()(Error, __LINE__, "file close lose");
            return false;
        }
    }
    return true;
}

#endif
